﻿namespace Fiddler
{
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Drawing;
    using System.Globalization;
    using System.Text;
    using System.Windows.Forms;

    internal class SessionProperties : Form
    {
        private Container components;
        private Session mySession;
        private StatusBar sbStatus;
        private RichTextBox txtProperties;

        internal SessionProperties(Session oSession)
        {
            this.InitializeComponent();
            this.txtProperties.BackColor = CONFIG.colorDisabledEdit;
            this.txtProperties.Font = new Font(this.txtProperties.Font.FontFamily, CONFIG.flFontSize);
            this.mySession = oSession;
            this.RefreshInfo();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        public static string GetSessionProperties(Session oS)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("SESSION STATE: {0}.\n", oS.state.ToString("g"));
            switch (oS.state)
            {
                case SessionStates.ReadingRequest:
                    long num;
                    builder.AppendFormat("UPLOAD PROGRESS: {0:N0}", oS.oRequest._PeekUploadProgress);
                    if ((oS.oRequest["Content-Length"] != string.Empty) && long.TryParse(oS.oRequest["Content-Length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out num))
                    {
                        builder.AppendFormat(string.Format(" of {0:N0}", num), new object[0]);
                    }
                    builder.Append(" bytes.\n\n");
                    break;

                case SessionStates.ReadingResponse:
                    long num2;
                    builder.AppendFormat("DOWNLOAD PROGRESS: {0:N0}", oS.oResponse._PeekDownloadProgress);
                    if ((oS.oResponse["Content-Length"] != string.Empty) && long.TryParse(oS.oResponse["Content-Length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out num2))
                    {
                        builder.AppendFormat(string.Format(" of {0:N0}", num2), new object[0]);
                    }
                    builder.Append(" bytes.\n\n");
                    goto Label_0146;
            }
        Label_0146:
            if ((oS.state >= SessionStates.SendingRequest) && oS.isFlagSet(SessionFlags.SentToGateway))
            {
                builder.Append("The request was forwarded to the gateway.\n");
            }
            if ((oS.requestBodyBytes != null) && (oS.requestBodyBytes.Length > 0))
            {
                builder.AppendFormat("Request Entity Size: {0:N0} bytes.\n", oS.requestBodyBytes.LongLength.ToString());
            }
            if (oS.responseBodyBytes != null)
            {
                builder.AppendFormat("Response Entity Size: {0:N0} bytes.\n", oS.responseBodyBytes.LongLength.ToString());
            }
            builder.Append("\n== FLAGS ==================\n");
            builder.AppendFormat("BitFlags: [{0}] 0x{1}\n", oS.BitFlags, ((int) oS.BitFlags).ToString("x"));
            foreach (DictionaryEntry entry in oS.oFlags)
            {
                builder.AppendFormat("{0}: {1}\n", (entry.Key as string).ToUpper(CultureInfo.InvariantCulture), entry.Value);
            }
            builder.Append("\n== TIMING INFO ============\n");
            DateTime clientBeginRequest = oS.Timers.ClientBeginRequest;
            if (((clientBeginRequest.Ticks > 0) && (clientBeginRequest.Date != DateTime.Today)) && (clientBeginRequest < DateTime.Now.AddHours(-2.0)))
            {
                builder.AppendFormat("\r\nThis traffic was captured on {0}.\r\n\r\n", clientBeginRequest.Date.ToLongDateString());
            }
            builder.Append(oS.Timers.ToString(true));
            if (oS.state >= SessionStates.ReadingResponse)
            {
                builder.Append(oS.isFlagSet(SessionFlags.ResponseStreamed) ? "\nThe response was streamed to the client as it was received.\n" : "\nThe response was buffered before delivery to the client.\n");
            }
            builder.Append("\n== WININET CACHE INFO ============\n");
            builder.Append(WinINETCache.GetCacheItemInfo(oS.fullUrl));
            builder.Append("\n* Note: Data above shows WinINET's current cache state, not the state at the time of the request.\n");
            if (Environment.OSVersion.Version.Major > 5)
            {
                builder.Append("* Note: Data above shows WinINET's Medium Integrity (non-Protected Mode) cache only.\n");
            }
            builder.Append("\n");
            return builder.ToString();
        }

        private void InitializeComponent()
        {
            this.sbStatus = new System.Windows.Forms.StatusBar();
            this.txtProperties = new System.Windows.Forms.RichTextBox();
            this.SuspendLayout();
            // 
            // sbStatus
            // 
            this.sbStatus.Location = new System.Drawing.Point(0, 531);
            this.sbStatus.Name = "sbStatus";
            this.sbStatus.Size = new System.Drawing.Size(516, 21);
            this.sbStatus.TabIndex = 1;
            this.sbStatus.Text = "Hit ESC to close, F5 to refresh.";
            // 
            // txtProperties
            // 
            this.txtProperties.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.txtProperties.DetectUrls = false;
            this.txtProperties.Dock = System.Windows.Forms.DockStyle.Fill;
            this.txtProperties.Font = new System.Drawing.Font("Lucida Console", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.txtProperties.Location = new System.Drawing.Point(0, 0);
            this.txtProperties.Name = "txtProperties";
            this.txtProperties.ReadOnly = true;
            this.txtProperties.Size = new System.Drawing.Size(516, 531);
            this.txtProperties.TabIndex = 2;
            this.txtProperties.Text = "";
            this.txtProperties.WordWrap = false;
            // 
            // SessionProperties
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.ClientSize = new System.Drawing.Size(516, 552);
            this.Controls.Add(this.txtProperties);
            this.Controls.Add(this.sbStatus);
            this.KeyPreview = true;
            this.Name = "SessionProperties";
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
            this.Text = "Session Properties";
            this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.SessionProperties_KeyUp);
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.SessionProperties_KeyDown);
            this.ResumeLayout(false);

        }

        private void RefreshInfo()
        {
            try
            {
                this.Text = string.Concat(new object[] { "Session Properties (", this.mySession.id, ") ", this.mySession.url });
                this.txtProperties.Text = GetSessionProperties(this.mySession);
                this.txtProperties.Select(0, 0);
            }
            catch (Exception exception)
            {
                this.txtProperties.Clear();
                this.txtProperties.AppendText(exception.Message + "\r\n" + exception.StackTrace);
            }
        }

        private void SessionProperties_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
            {
                this.RefreshInfo();
            }
        }

        private void SessionProperties_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                e.SuppressKeyPress = true;
                base.Close();
            }
        }
    }
}

